package protocols

import (
	"fmt"
	"net/url"
	"strings"
)

// Known protocols
const (
	HTTP    = "http"
	HTTPS   = "https"
	FTP     = "ftp"
	FTPS    = "ftps"
	SFTP    = "sftp"
	MAGNET  = "magnet"
	TORRENT = "torrent"
	ED2K    = "ed2k"
)

// DetectProtocol determines the protocol from a URL string
func DetectProtocol(urlStr string) string {
	// 定义特殊协议的前缀映射
	specialProtocols := map[string]string{
		"magnet:": MAGNET,
		"ed2k://": ED2K,
	}

	// 检查特殊协议
	for prefix, protocol := range specialProtocols {
		if strings.HasPrefix(urlStr, prefix) {
			return protocol
		}
	}

	// 解析URL
	u, err := url.Parse(urlStr)
	if err != nil {
		// 这里可以考虑使用日志库代替fmt.Printf，当前仅简单输出错误信息
		fmt.Printf("解析url失败: %v\n", err)
		return ""
	}

	// 检查scheme
	scheme := strings.ToLower(u.Scheme)
	supportedSchemes := map[string]bool{
		HTTP:  true,
		HTTPS: true,
		FTP:   true,
		FTPS:  true,
		SFTP:  true,
	}
	if supportedSchemes[scheme] {
		return scheme
	}

	// 检查文件扩展名是否为.torrent
	if strings.HasSuffix(strings.ToLower(u.Path), ".torrent") {
		return TORRENT
	}

	return ""
}

// IsSupportedProtocol checks if the protocol is supported
func IsSupportedProtocol(protocol string) bool {
	if protocol == "" {
		return false
	}
	supportedProtocols := map[string]bool{
		HTTP: true, HTTPS: true, FTP: true, FTPS: true,
		SFTP: true, MAGNET: true, TORRENT: true, ED2K: true,
	}
	_, exists := supportedProtocols[protocol]
	return exists
}
